<?php

namespace app\api\controller;

use app\admin\model\Paper;
use app\admin\model\Config;
use app\admin\model\Order;
use app\api\model\System as SystemModel;
use app\api\model\User as UserModel;
use app\BaseController;
use app\lib\MiniWechat;
use app\lib\tool\Str;
use think\facade\Cache;
use think\Request;

class User extends BaseController
{
    /* 自动加载 */
    public function initialize()
    {
        $this->uid = $this->request->uid;
    }

    /* 检测token合法性 */
    public function checkToken()
    {
        if (!$this->request->auth) {
            return show(config('status.auth'), 'Authorization Failed');
        } else {
            return show(config('status.success'), 'Token合法');
        }
    }

    /* 授权登录[H5] */
    public function login()
    {
        $mini = new MiniWechat;
        $data = $mini->code2Session(input('code', ''));
        if (!is_array($data) || !array_key_exists('session_key', $data) || !array_key_exists('openid', $data) ) {
            return show($data['errcode'], '微信获取信息失败：' . $data['errmsg']);
        }

        $openId = $data['openid'];
//        $openId = 'oSCT25YW5sDE8piiJArc27Q5o1W8';
        $userInfo = \app\admin\model\User::where('openid', $openId)->find();
        if (!empty($userInfo)) {
            $userInfo->wxname = input('post.wxname');
            $userInfo->wximage = input('post.wximage');
            $userInfo->save();
        } else {
            $userInfo = UserModel::create([
                'wxname' => input('post.wxname'),
                'wximage'=> input('post.wximage'),
                'openid' => $openId,
                'phone'  => ''
            ]);
        }
        $userInfo = $userInfo->toArray();
        $userInfo['session_key'] = $data['session_key'];
        $token = Str::getToken();
        Cache::set(config('cache.stores.redis.prefix') . $token, $userInfo, config('cache.stores.redis.timeout'));
        return show(config('status.success'), '登录成功', ['token' => $token]);
    }

    // 订单详情
    public function findOrder()
    {
        $order = \app\admin\model\Paper::where('id', \request()->post('id'))->where([
            'is_pay' => 1,
        ])->find();
        return show(config('status.success'),  'success', $order);
    }

    // 提交评论
    public function submitComment()
    {
        $order = \app\admin\model\Paper::where('id', \request()->post('id'))->where('user_id', \request()->uid)->update([
            'student_comment' => \request()->post('comment'),
        ]);
        return show(config('status.success'),  'success', $order);
    }

    // 订单列表
    public function getOrders()
    {
        $orders = \app\admin\model\Paper::where('user_id', \request()->uid)->where([
            'is_pay' => 1,
            'is_read' => \request()->post('is_read', 0)
        ])->order('id desc')->select();
        return show(config('status.success'),  'success', $orders);
    }

    // 设置姓名
    public function updateName()
    {
//        if (! $this->request->auth) {
//            return show(config('status.error'), '请登录');
//        }
        $userId = request()->uid;
//        $userId = 1;
        \app\admin\model\User::where('id', $userId)->update(['name' => \request()->post('name')]);
        return show(config('status.success'),  'success');
    }

    // 修改密码
    public function updatePwd()
    {
        if (! $this->request->auth) {
            return show(config('status.error'), '请登录');
        }
        $password = $this->request->post('oldpwd');
        $newPassword = $this->request->post('new_password');
        if (empty($password)) {
            return show(-1, '请填写原密码');
        }
        if (strlen($newPassword) < 6) {
            return show(-1, '新密码不得少于六位');
        }

        $user = \app\admin\model\User::find(\request()->uid);
        if ($user->web_password != get_password($password)) {
            return show(-1, '密码不正确');
        }

        $user->web_password = get_password($newPassword);
        $user->save();
        return show(config('status.success'),  'success');
    }

    public function createReocrd(Request $request)
    {
//        if (! $this->request->auth) {
//            return show(config('status.error'), '请登录');
//        }

        $paper = Paper::create([
            'user_id' => \request()->uid,
            'type' => $request->post('type'),
            'paper_type' => $request->post('paper_type'),
            'subject_type' => $request->post('subject_type'),
            'year' => $request->post('year'),
            'pics' => $request->post('pics'),
            'paper_pics' => $request->post('paper_pics'),
            'title' => $request->post('title'),
            'content' => $request->post('content'),
            'order_num' => buildOrderNum(),
            'is_attr' => $request->post('is_attr', 0),
        ]);

        return show(config('status.success'),  'success', [
            'order_num' => $paper->order_num
        ]);
    }

    // 支付
    public function pay(Request $request)
    {
        $userInfo = request()->userInfo;
        $orderNo = request()->post("order_no");
        $order = Paper::where(['order_num' => $orderNo])->find();
        if (empty($order)) {
            return show(config('status.error'), '订单不存在');
        }
        $price = Config::where('key', 'price')->value('value');
        $order->wechat_order_num = 'w' . buildOrderNum();
        $order->price = $price;
        $wechat = new MiniWechat();
        try {
            $result = $wechat->createOrder([
                'body' => '订单',
                'out_trade_no' => $order->wechat_order_num,
                'openid' => $userInfo['openid'],
                'total_fee' => round($price * 100),
                'trade_type' => 'JSAPI',
                'notify_url' => request()->domain() . '/api/pay/wechatNotifyByPackagePay',
                'spbill_create_ip' => '127.0.0.1',
            ]);
            $order->wechat_placeorder_res_data = json_encode($result);
            $order->save();
        } catch (\Exception $e) {
            return show(config('status.error_system'), '微信下单失败：' . $e->getMessage());
        }


        return show(config('status.success'), '操作成功', $result);
    }
    
    // 上传图片
    public function uploadImage()
    {
        // 获取表单上传文件l
        $files = request()->file();
        try {
            validate(['image'=>'filesize:209715'])
                ->check($files);
            $savename = [];
            foreach($files as $file) {
                $savename[] = \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
            }
            return show(config('status.success'), '操作成功', ['path' => \request()->domain().'/storage/'. $savename[0]]);
        } catch (\think\exception\ValidateException $e) {
            return show(config('status.error_system'),  $e->getMessage());
        }
    }

    // 绑定手机号
    public function bindPhoneNumber()
    {
       if (!$this->request->auth) {
            return show(config('status.error'), '请登录');
        }
        $userInfo = request()->userInfo;
        $encryptedData = input('post.encryptedData');
        $iv = input('post.iv');
        if (empty($encryptedData) || empty($iv))  {
            return show(config('status.error_system'), '缺少必要参数');
        }

        $mini = new MiniWechat;
        $data = $mini->code2Session(input('code', ''));
        $result = $mini->decode($iv, $data['session_key'], $encryptedData);
        if (!is_array($result) || !array_key_exists('phoneNumber', $result)) {
            return show(config('status.error_system'), '手机号获取失败：'. (is_array($result) ? $result['errMsg'] : ''));
        }
        UserModel::where('id', $userInfo['id'])->update(['phone' => $result['phoneNumber'], 'web_password' => get_password(substr($result['phoneNumber'], -6))]);
        return show(config('status.success'), '绑定成功', ['phone' => $result['phoneNumber']]);
    }

    /**
     * 获取用户信息
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserInfo(Request $request)
    {
        if (!$this->request->auth) {
            return show(config('status.error'), '请登录');
        }
        $user = \app\api\model\User::field('id,wxname,wximage,name,phone')->where('id', $this->request->uid)->find();
        if (empty($user)) {
            return show(config('status.success'), 'success', []);
        }
        if (empty($user->wxname))  $user->wxname='';
        if (empty($user->wximage)) $user->wximage='';
        return show(config('status.success'), 'success', $user);
    }

    /* 设置 */
    public function setInfo()
    {
        if (!$this->request->auth) return show(config('status.auth'), 'Authorization Failed');
        $field = input('field', '');
        $value = input('value', '');
        UserModel::update([
            'id' => $this->request->uid,
            $field => $value
        ]);
        return show(config('status.success'), '设置用户信息');
    }

    /**
     * 学生端登录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function webLogin()
    {

        $phone = \request()->post('phone');
        $password = \request()->post('password');
        $user = \app\admin\model\User::where('phone', $phone)->find();
        if (empty($user)) {
            return show(config('status.error'), '用户不存在');
        }
        if (get_password($password) != $user->web_password) {
            return show(config('status.error'), '密码不正确');
        }

        $token = Str::getToken();
        Cache::set('web_user' . $token, $user, config('cache.stores.redis.timeout'));

        return show(config('status.success'), '登录成功', ['token' => $token]);
    }

    public function getMyOrders()
    {
        $userInfo = $this->getMyUserInfo();
        if (empty($userInfo)) {
            return show(config('status.error'), '请登陆');
        }

        $orders = Paper::where([
            'is_attr' =>1,
            'is_pay' => 1,
            'user_id' => $userInfo['id'],
        ])->field('id,title,type,paper_type,subject_type,attr_files')->select();

        return show(config('status.success'), 'success',  $orders);
    }

    private function getMyUserInfo()
    {
        return Cache::get('web_user' . \request()->post('Authorization'));
    }

    # 获取用户信息
    public function getWebUseriNfo()
    {
        $userInfo = $this->getMyUserInfo();
        if (empty($userInfo)) {
            return show(config('status.error'), '请登陆');
        }

        $info = [
            'name' => $userInfo['name'],
            'wximage' => $userInfo['wximage'],
            'wxname' => $userInfo['wxname']
        ];
        return show(config('status.success'),'success', $info);
    }

    // 更新附件
    public function updateEnclosure()
    {
        $userInfo = $this->getMyUserInfo();
        if (empty($userInfo)) {
            return show(config('status.error'), '请登陆');
        }
        $id = \request()->post('id');
        $order = Paper::where('id', $id)->where([
            'user_id' => $userInfo['id']
        ])->find();
        $attr_files =$order->attr_files . \request()->post('attr_files');
        $attr_files = '"'.$attr_files .'"';
        Paper::where('id', $id)->where([
            'user_id' => $userInfo['id']
        ])->update(['attr_files'=>$attr_files]);
        return show(config('status.success'),'success');
    }
}
